//
//  XLRealTimeViewController.m
//  RealTimeSigns
//
//  Created by 于鹏 on 2017/9/7.
//  Copyright © 2017年 YIVIEW. All rights reserved.
//

#import "XLRealTimeViewController.h"
#import "XLECGView.h"
//#import <BaseModule/GCDAsyncSocketManager.h>
//#import <Masonry.h>
#import "GCDAsyncSocketManager.h"
#import "Masonry.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "MonitorModel.h"
#import "FunProgressHUD.h"
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define kBtmView_H      50
#define margin  0

@interface XLRealTimeViewController ()<TCPAsyncSocketDelegate>
@property (nonatomic, strong)NSMutableData *ecgData;
@property (nonatomic, strong)NSMutableArray *ecgDataSource;
@property (nonatomic, strong)NSMutableData *ecg2Data;
@property (nonatomic, strong)NSMutableArray *ecg2DataSource;
@property (nonatomic, strong)NSMutableData *spo2Data;
@property (nonatomic, strong)NSMutableArray *spo2DataSource;
@property (nonatomic, strong)NSMutableData *respData;
@property (nonatomic, strong)NSMutableArray *respDataSource;
@property (nonatomic, strong)XLECGView *ecgView;
@property (nonatomic, strong)XLECGView *ecg2View;
@property (nonatomic, strong)XLECGView *spo2View;
@property (nonatomic, strong)XLECGView *respView;

@property (nonatomic, strong)NSData *appendData;//数据占包时 将上一包剩余数据拼接到下一包起始数据
@property (nonatomic, strong) UIButton *bindInstrument; //解绑仪器/绑定仪器
/**
 定时刷新数据
 */
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) BOOL isBind;

@property (nonatomic, strong) NSMutableArray *monitorArr;

@end

@implementation XLRealTimeViewController
{
    CGFloat _height;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    for (UIView *subView in self.view.subviews) {
        if ([subView isKindOfClass:[XLECGView class]]) {
            XLECGView *ecgV = (XLECGView *)subView;
            [ecgV invalidTimer];
        }
    }
        [self closeTimer];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [TCPSocketManager_instance disconnectSocket];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"实时体征";
    
    CGFloat top = 10;
    CGFloat bottom = 10;
    int count = 3;
//    _height =(KScreenHeight - margin*(count-1)-top-bottom - 64-50-20)/count;
    _height =(KScreenHeight - margin*(count-1)-top-bottom - 64)/count;

    [self.view addSubview:self.ecgView];
    //    [self.view addSubview:self.ecg2View];
    [self.view addSubview:self.spo2View];
    [self.view addSubview:self.respView];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshData) userInfo:nil repeats:YES];
    //开启定时器
    [self.timer setFireDate:[NSDate distantPast]];
    
    [self initTCP];
    
    self.monitorArr = [NSMutableArray array];
    
    [self setupRightBarItemWithTitle:@"截图" action:@selector(screenshotAction:)];
    
}

#pragma mark - 专家端数据处理
- (void)initTCP {
    [TCPSocketManager_instance changeHost:UserInfo.serviceInfo.serviceAddress port:UserInfo.serviceInfo.port.intValue];
    [TCPSocketManager_instance connectSocket];
    TCPSocketManager_instance.tcpSocketDelegate = self;
}
#pragma mark - TCPAsyncSocketDelegate
- (void)tcpSocketReadedData:(NSData *)data {
    if (data.length == 0) {
        return;
    }
    XLLog(@"接收到的原始数据:%@",data);
    NSMutableData *stickPackageData = [NSMutableData data];//拼接上一包剩余的数据
    if (self.appendData.length > 0) {
        [stickPackageData appendData:self.appendData];
    }
    [stickPackageData appendData:data];
    //    XLLog(@"拆包后的数据:%@",stickPackageData);
    
    //判断开始数据是否为心跳包
    NSData *beatData =  TCPSocketManager_instance.sendBeatData;//心跳包数据

    Byte bufRecv[stickPackageData.length];
    for (int i = 0; i < stickPackageData.length; i++) {
        Byte byte = ((Byte *)([stickPackageData bytes]))[i];
        bufRecv[i] = byte;
    }
    //处理粘包,根据数据长度,取出数据
    
    int index = 0;
    while (sizeof(bufRecv) > index) {
        
        //        //删除心跳包数据
        NSRange beatRange = NSMakeRange(index, beatData.length);
        if (stickPackageData.length > beatRange.location+beatRange.length) {
            NSData *subData = [NSData dataWithData:[stickPackageData subdataWithRange:beatRange]];
            if ([beatData isEqualToData:subData]) {
                [stickPackageData replaceBytesInRange:beatRange withBytes:NULL length:0];
                XLLog(@"删除心跳包之后的数据:%@",stickPackageData);
                
            }
        }
        
        if (stickPackageData.length == 0) {return;}
        
        WAVETYPE *waveType = (WAVETYPE *)&bufRecv[index];
        short length = waveType->length;
        NSRange range = NSMakeRange(index, 3+length);
        if (range.location+range.length > stickPackageData.length) {//如果所取的范围>整体数据的长度 拼接到下一个包
            range.length = stickPackageData.length - index;
            self.appendData = [NSData dataWithData:[stickPackageData subdataWithRange:range]];
            return;
        }
        //整体数据(类型+长度+波形数据)
        NSData *subdata = [stickPackageData subdataWithRange:range];
        //        NSLog(@"subdata:%@",subdata);
        //获取波形图数据
        NSData *waveData = [subdata subdataWithRange:NSMakeRange(3, length)];
        Byte type = ((Byte *)([subdata bytes]))[0];
        MonitorModel *model = [[MonitorModel alloc]init];
        model.pkgType = type;
        [self tcpDataWithType:model.pkgType waveData:waveData];
        index += subdata.length;
    }
    
}
- (void)tcpDataWithType:(PKGTYPE)type waveData:(NSData *)waveData {
    switch (type) {
        case pkg_0x90:{
            //XLLog(@"ECG1:%@",waveData);
            [self xl_getECGData:waveData];
            break;
        }
        case pkg_0x91:{
            //XLLog(@"ECG2:%@",waveData);
            break;
        }
        case pkg_0x92:{
            //XLLog(@"spo2:%@",waveData);
            [self xl_getSPO2Data:waveData];
            
            break;
        }
        case pkg_0x93:{
            //XLLog(@"RESP:%@",waveData);
            [self xl_getRESPData:waveData];
            break;
        }
        default:
            break;
    }
}
- (void)xl_getECGData:(NSData *)fromData {
    if (self.ecgData.length >= maxECGCount) {
        [self.ecgData resetBytesInRange:NSMakeRange(0, self.ecgData.length)];
        [self.ecgData setLength:0];
    }
    [self.ecgData appendData:fromData];
    
    if (self.ecgData.length == maxECGCount) {
        self.ecgDataSource = [NSMutableArray array];
        Byte *testByte = (Byte *)[self.ecgData bytes];
        for(int i=0;i<[self.ecgData length];i++){
            int intv = testByte[i];
            NSNumber *number = [NSNumber numberWithInt:intv];
            [self.ecgDataSource addObject:number];
        }
        self.ecgView.ecgDataSource = self.ecgDataSource;
        [self.ecgView createWorkDataSourceWithTimeInterval:1.0/EcgWaveLength];
    }
}

- (void)xl_getRESPData:(NSData *)fromData {
    if (self.respData.length >= maxRESPCount) {
        [self.respData resetBytesInRange:NSMakeRange(0, self.respData.length)];
        [self.respData setLength:0];
    }
    [self.respData appendData:fromData];
    
    if (self.respData.length == maxRESPCount) {
        self.respDataSource = [NSMutableArray array];
        Byte *testByte = (Byte *)[self.respData bytes];
        for(int i=0;i<[self.respData length];i++){
            int intv = testByte[i];
            NSNumber *number = [NSNumber numberWithInt:intv];
            [self.respDataSource addObject:number];
        }
        self.respView.ecgDataSource = self.respDataSource;
        [self.respView createWorkDataSourceWithTimeInterval:1.0/RespWaveLength];
    }
}
- (void)xl_getSPO2Data:(NSData *)fromData {
    if (self.spo2Data.length >= maxSPO2Count) {
        [self.spo2Data resetBytesInRange:NSMakeRange(0, self.spo2Data.length)];
        [self.spo2Data setLength:0];
    }
    [self.spo2Data appendData:fromData];
    
    if (self.spo2Data.length == maxSPO2Count) {
        self.spo2DataSource = [NSMutableArray array];
        Byte *testByte = (Byte *)[self.spo2Data bytes];
        for(int i=0;i<[self.spo2Data length];i++){
            int intv = testByte[i];
            NSNumber *number = [NSNumber numberWithInt:intv];
            [self.spo2DataSource addObject:number];
        }
        self.spo2View.ecgDataSource = self.spo2DataSource;
        [self.spo2View createWorkDataSourceWithTimeInterval:1.0/RespWaveLength];
    }
}

- (void)configureEcgView:(XLECGView *)ecgView des1Text:(NSString *)des1Text des1Color:(UIColor *)des1Color des2Text:(NSString *)des2Text des2Color:(UIColor *)des2Color {
    ecgView.des1Label.text = des1Text;
    ecgView.des1Label.textColor = des1Color;
    ecgView.des2Label.text = des2Text;
    ecgView.des2Label.textColor = des2Color;
}

- (void)initData {
    [super initData];
//    [self refreshData];
}

- (void)refreshData {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setValue:self.emergencyTreatmentID forKey:@"TreatmentID"];
        [parameters setValue:UserInfo.userID forKey:@"doctorID"];
        [parameters setValue:UserInfo.tokenCode forKey:@"token"];
   
    [XLHTTPRequest ETM_getRealTimeDataWithParameters:parameters success:^(id responseObject) {
        
        id object = responseObject[@"data"];
        if ([object isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = object;
            //心率,血压
            [self configureEcgView:self.ecgView des1Text:[NSString stringWithFormat:@"心率:\n%@",dic[@"HeartRate_1"]] des1Color:CurveStrokeColorOfGreen des2Text:[NSString stringWithFormat:@"NIBP:\n%@/%@",dic[@"BloodHighPressure"],dic[@"BloodLowPressure"]] des2Color:DefaultTextColor];
            //呼吸率,体温
            NSNumber *t1 = dic[@"Temperature_1"];
            NSNumber *t2 = dic[@"Temperature_2"];
            [self configureEcgView:self.respView des1Text:[NSString stringWithFormat:@"呼吸率:\n%@",dic[@"RespiratoryRate"]] des1Color:CurveStrokeColorOfYellow des2Text:[NSString stringWithFormat:@"体温1:\n%.1f\n体温2:\n%.1f",t1.floatValue/10.0,t2.floatValue/10.0] des2Color:DefaultTextColor];
            [self configureEcgView:self.spo2View des1Text:[NSString stringWithFormat:@"血氧:\n%@",dic[@"Oxygen"]] des1Color:CurveStrokeColorOfRed des2Text:[NSString stringWithFormat:@"脉率:\n%@",dic[@"PulseRate"]] des2Color:CurveStrokeColorOfRed];
        }
    } failure:^(NSError *error, NSString *info) {
        if (error == nil) {
          [self showErrorInfo:info];
        }
        [self closeTimer];
        
        NSString *tip = @"无数据";
        [self configureEcgView:self.ecgView des1Text:tip des1Color:DefaultTextColor des2Text:tip des2Color:DefaultTextColor];
        [self configureEcgView:self.respView des1Text:tip des1Color:DefaultTextColor des2Text:tip des2Color:DefaultTextColor];
        [self configureEcgView:self.spo2View des1Text:tip des1Color:DefaultTextColor des2Text:tip des2Color:DefaultTextColor];
    }];
}

- (void)showErrorInfo:(NSString *)info {
    [self dismissHUD];
    NSString *tipMessage = ISNILORNULL(info);
    if ([tipMessage containsString:LOGIN_STR]) {
        UserInfo.isLogin = NO;
        [UserInfo synchronize];
        [self showLoginAlert];
        
    }else{
        UIAlertView *tipAlert = [[UIAlertView alloc]initWithTitle:@"提示" message:info delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [tipAlert show];
    }
}

//- (void)refreshData {
//    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
////    [parameters setValue:self.emergencyTreatmentID forKey:@"TreatmentID"];
////    [parameters setValue:UserInfo.userID forKey:@"doctorID"];
////    [parameters setValue:UserInfo.tokenCode forKey:@"token"];
//    [parameters setValue:self.emergencyTreatmentID forKey:@"EmergencyTreatmentID"];
//    [parameters setValue:UserInfo.userID forKey:@"DoctorID"];
//    [parameters setValue:UserInfo.tokenCode forKey:@"TokenCode"];
//    [XLHTTPRequest ETM_getRealTimeDataWithParameters:parameters success:^(id responseObject) {
//        if ([responseObject[@"IsSuccessful"] integerValue] == 1){
//            NSDictionary *dic = responseObject[@"_info"];
//            //心率,血压
//            [self configureEcgView:self.ecgView des1Text:[NSString stringWithFormat:@"心率:\n%@",dic[@"HeartRate_1"]] des1Color:CurveStrokeColorOfGreen des2Text:[NSString stringWithFormat:@"NIBP:\n%@/%@",dic[@"BloodHighPressure"],dic[@"BloodLowPressure"]] des2Color:DefaultTextColor];
//            //呼吸率,体温
//            NSNumber *t1 = dic[@"Temperature_1"];
//            NSNumber *t2 = dic[@"Temperature_2"];
//            [self configureEcgView:self.respView des1Text:[NSString stringWithFormat:@"呼吸率:\n%@",dic[@"RespiratoryRate"]] des1Color:CurveStrokeColorOfYellow des2Text:[NSString stringWithFormat:@"体温1:\n%.1f\n体温2:\n%.1f",t1.floatValue/10.0,t2.floatValue/10.0] des2Color:DefaultTextColor];
//            [self configureEcgView:self.spo2View des1Text:[NSString stringWithFormat:@"血氧:\n%@",dic[@"Oxygen"]] des1Color:CurveStrokeColorOfRed des2Text:[NSString stringWithFormat:@"脉率:\n%@",dic[@"PulseRate"]] des2Color:CurveStrokeColorOfRed];
//        }
//
//    } failure:^(NSError *error, NSString *info) {
//            if (error == nil) {
//                [self exitLogin:info];
//            }
//        }];
//}

#pragma mark - Getter
- (XLECGView *)ecgView {
    if (!_ecgView) {
        _ecgView = [[XLECGView alloc]initWithFrame:CGRectMake(0, 10, KScreenWidth, _height)];
        _ecgView.backgroundColor = XLECGViewBGCOLOR;
        _ecgView.maxContainerCapacity = maxECGCount;
        _ecgView.curveStrokeColor = CurveStrokeColorOfGreen;
    }
    return _ecgView;
}

- (XLECGView *)ecg2View {
    if (!_ecg2View) {
        _ecg2View = [[XLECGView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.ecgView.frame)+10, KScreenWidth, _height)];
        _ecg2View.backgroundColor = XLECGViewBGCOLOR;
        _ecg2View.maxContainerCapacity = maxECGCount;
        _ecg2View.curveStrokeColor = CurveStrokeColorOfGreen;
    }
    return _ecg2View;
}

- (XLECGView *)spo2View {
    if (!_spo2View) {
        
        _spo2View = [[XLECGView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.ecgView.frame)+margin, KScreenWidth, _height)];
        _spo2View.backgroundColor = XLECGViewBGCOLOR;
        _spo2View.maxContainerCapacity = maxSPO2Count;
        _spo2View.curveStrokeColor = CurveStrokeColorOfRed;
    }
    return _spo2View;
}

- (XLECGView *)respView {
    if (!_respView) {
        _respView = [[XLECGView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.spo2View.frame)+margin, KScreenWidth, _height)];
        _respView.backgroundColor = XLECGViewBGCOLOR;
        _respView.maxContainerCapacity = maxRESPCount;
        _respView.curveStrokeColor = CurveStrokeColorOfYellow;
    }
    return _respView;
}

- (NSMutableData *)ecgData {
    if (!_ecgData) {
        _ecgData = [[NSMutableData alloc]init];
    }
    return _ecgData;
}
- (NSMutableData *)ecg2Data {
    if (!_ecg2Data) {
        _ecg2Data = [[NSMutableData alloc]init];
    }
    return _ecg2Data;
}
- (NSMutableData *)respData {
    if (!_respData) {
        _respData = [[NSMutableData alloc]init];
    }
    return _respData;
}
- (NSMutableData *)spo2Data {
    if (!_spo2Data) {
        _spo2Data = [[NSMutableData alloc]init];
    }
    return _spo2Data;
}

#pragma mark - 关闭定时器
- (void)closeTimer
{
    if (self.timer != nil) {
        //取消定时器
        [self.timer invalidate];
        self.timer = nil;
        //关闭定时器
        [self.timer setFireDate:[NSDate distantFuture]];
    }
}

#pragma mark - 截图
- (void)screenshotAction:(id)sender {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 && [[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
        
        [FunProgressHUD showInfoWithStatus:@"iphone8.0以下系统暂不支持截屏"];
        
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        NSString *tipTextWhenNoPhotosAuthorization; // 提示语
        // 获取当前应用对照片的访问授权状态
        ALAuthorizationStatus authorizationStatus = [ALAssetsLibrary authorizationStatus];
        // 如果没有获取访问授权，或者访问授权状态已经被明确禁止，则显示提示语，引导用户开启授权
        if (authorizationStatus == ALAuthorizationStatusRestricted || authorizationStatus == ALAuthorizationStatusDenied) {
            NSDictionary *mainInfoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString *appName = [mainInfoDictionary objectForKey:@"CFBundleDisplayName"];
            tipTextWhenNoPhotosAuthorization = [NSString stringWithFormat:@"请在设备的\"设置-隐私-照片\"选项中，允许%@访问你的手机相册", appName];
            // 展示提示语
        } else {
            
            //            UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow];
            //            UIGraphicsBeginImageContext(screenWindow.frame.size);
            //            [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
            //            UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
            //            UIGraphicsEndImageContext();
            //            UIImageWriteToSavedPhotosAlbum(img, nil, nil,nil);
            
            UIImageWriteToSavedPhotosAlbum([self getImageWithFullScreenshot], nil, nil,nil);
            [FunProgressHUD showSuccessWithStatus:@"截图已保存在相册中"];
        }
    }
}

- (UIImage *)getImageWithFullScreenshot
{
    // Source (Under MIT License): https://github.com/shinydevelopment/SDScreenshotCapture/blob/master/SDScreenshotCapture/SDScreenshotCapture.m#L35
    
    BOOL ignoreOrientation = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0");
    
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    
    CGSize imageSize = CGSizeZero;
    if (UIInterfaceOrientationIsPortrait(orientation) || ignoreOrientation)
        imageSize = [UIScreen mainScreen].bounds.size;
    else
        imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
    
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    for (UIWindow *window in [[UIApplication sharedApplication] windows])
    {
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, window.center.x, window.center.y);
        CGContextConcatCTM(context, window.transform);
        CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
        
        // Correct for the screen orientation
        if(!ignoreOrientation)
        {
            if(orientation == UIInterfaceOrientationLandscapeLeft)
            {
                CGContextRotateCTM(context, (CGFloat)M_PI_2);
                CGContextTranslateCTM(context, 0, -imageSize.width);
            }
            else if(orientation == UIInterfaceOrientationLandscapeRight)
            {
                CGContextRotateCTM(context, (CGFloat)-M_PI_2);
                CGContextTranslateCTM(context, -imageSize.height, 0);
            }
            else if(orientation == UIInterfaceOrientationPortraitUpsideDown)
            {
                CGContextRotateCTM(context, (CGFloat)M_PI);
                CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
            }
        }
        
        if([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
            [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:NO];
        else
            [window.layer renderInContext:UIGraphicsGetCurrentContext()];
        
        CGContextRestoreGState(context);
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
